﻿using AutoMapper;
using MediatR;
using NPOI.SS.Formula.Functions;
using ProcurementManagement.Applcation.Command.ProcurementReturnCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.ProcurementReturnCommandHandler
{
    public class UpdProcurementReturnCommandHandler : IRequestHandler<UpdProcurementReturnCommand, int>
    {
        IPurchaseReturnsRepository prRep;
        IReturnProductRepository rpRep;
        IMapper mapper;
        ISqlSugarClient db;

        public UpdProcurementReturnCommandHandler(IPurchaseReturnsRepository prRep,
        IMapper mapper, ISqlSugarClient db, IReturnProductRepository rpRep)
        {
            this.prRep = prRep;
            this.mapper = mapper;
            this.db = db;
            this.rpRep = rpRep;
        }

        public async Task<int> Handle(UpdProcurementReturnCommand request, CancellationToken cancellationToken)
        {

            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //修改采购退货
                var se = await db.Queryable<PurchaseReturns>()
                                 .Where(c => c.PurchaseReturnsIds == request.UpdDto.PurchaseReturnsIds)
                                 .FirstAsync(); 

                var procurement1 = mapper.Map<PurchaseReturns>(request.UpdDto);
                var taskToAdd = await prRep.UpdataAsync(se);


                //删除采购退货中的数据
                var itemsToDelete = await db.Queryable<ReturnProduct>()
                                  .Where(c => c.PurchaseReturnsCode == se.PurchaseReturnsCode)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await rpRep.DelRange(new List<ReturnProduct> { item });
                }


                //修改采购退货产品
                foreach (var item in request.UpdDto.returnProductLists)
                {
                    ReturnProduct detail = new ReturnProduct();
                    detail.ProductId = item.ProductId;
                    detail.PurchaseReturnsCode = se.PurchaseReturnsCode;
                    detail.RPNum = item.RPNum;
                    detail.RPPrice = item.RPPrice;
                    detail.Office_Id = item.Office_Id;
                    detail.User_Id = item.User_Id;
                    await rpRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }


        }
    }
}
